<template>
  <div class="config-list">
    <div class="header-actions"><h2>MQ 配置列表</h2>
      <el-button type="primary" @click="openAddDialog">
        <el-icon>
          <Plus/>
        </el-icon>
        添加配置
      </el-button>
    </div>
    <el-table :data="configs" border stripe :max-height="700" style="width: 100%" v-loading="loading">
      <el-table-column type="index" label="序号" width="80"/>
      <el-table-column prop="businessName" label="配置名称" width="160"/>
      <el-table-column prop="messageType" label="消息类型" width="160"/>
      <el-table-column prop="exchangeName" label="交换机"/>
      <el-table-column prop="exchangeType" label="交换机类型"/>
      <el-table-column prop="queueName" label="队列"/>
      <el-table-column prop="routingKey" label="路由键"/>
      <el-table-column label="持久化" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.queueDurable ? 'success' : 'info'">{{ scope.row.queueDurable ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="启用" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.enabled ? 'success' : 'info'">{{ scope.row.enabled ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteConfig(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑配置弹框 -->
    <el-dialog v-model="editDialogVisible" title="编辑配置" width="800px" :before-close="handleEditDialogClose">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配置名称" prop="businessName">
              <el-input v-model="editForm.businessName" placeholder="请输入配置名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消息类型" prop="messageType">
              <el-input v-model="editForm.messageType" placeholder="请输入消息类型"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交换机名称" prop="exchangeName">
              <el-input v-model="editForm.exchangeName" placeholder="请输入交换机名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交换机类型" prop="exchangeType">
              <el-select v-model="editForm.exchangeType" placeholder="请选择交换机类型" style="width: 100%">
                <el-option label="direct" value="direct"/>
                <el-option label="topic" value="topic"/>
                <el-option label="fanout" value="fanout"/>
                <el-option label="headers" value="headers"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="队列名称" prop="queueName">
              <el-input v-model="editForm.queueName" placeholder="请输入队列名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由键" prop="routingKey">
              <el-input v-model="editForm.routingKey" placeholder="请输入路由键"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="队列持久化">
              <el-switch v-model="editForm.queueDurable"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交换机持久化">
              <el-switch v-model="editForm.exchangeDurable"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="队列自动删除">
              <el-switch v-model="editForm.queueAutoDelete"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="重试次数">
              <el-input-number v-model="editForm.maxRetryCount" :min="0" :max="10" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态">
              <el-switch v-model="editForm.enabled"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="失败后置方法" prop="failureHandlerClass">
          <el-input v-model="editForm.failureHandlerClass" placeholder="请输入失败后置方法类路径，如：com.example.handler.SmsNotificationHandler"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleEditDialogClose">取消</el-button>
          <el-button type="primary" @click="updateConfig" :loading="editLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加配置弹框 -->
    <el-dialog v-model="addDialogVisible" title="添加配置" width="800px" :before-close="handleAddDialogClose">
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配置名称" prop="businessName">
              <el-input v-model="addForm.businessName" placeholder="请输入配置名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消息类型" prop="messageType">
              <el-input v-model="addForm.messageType" placeholder="请输入消息类型"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交换机名称" prop="exchangeName">
              <el-input v-model="addForm.exchangeName" placeholder="请输入交换机名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交换机类型" prop="exchangeType">
              <el-select v-model="addForm.exchangeType" placeholder="请选择交换机类型" style="width: 100%">
                <el-option label="direct" value="direct"/>
                <el-option label="topic" value="topic"/>
                <el-option label="fanout" value="fanout"/>
                <el-option label="headers" value="headers"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="队列名称" prop="queueName">
              <el-input v-model="addForm.queueName" placeholder="请输入队列名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由键" prop="routingKey">
              <el-input v-model="addForm.routingKey" placeholder="请输入路由键"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="队列持久化">
              <el-switch v-model="addForm.queueDurable"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交换机持久化">
              <el-switch v-model="addForm.exchangeDurable"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="队列自动删除">
              <el-switch v-model="addForm.queueAutoDelete"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="重试次数">
              <el-input-number v-model="addForm.maxRetryCount" :min="0" :max="10" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态">
              <el-switch v-model="addForm.enabled"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="失败后置方法" prop="failureHandlerClass">
          <el-input v-model="addForm.failureHandlerClass" placeholder="请输入失败后置方法类路径，如：com.example.handler.SmsNotificationHandler"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleAddDialogClose">取消</el-button>
          <el-button type="primary" @click="addConfig" :loading="addLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, inject, nextTick} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessageBox, ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {mqConfigApi} from '../api'

const router = useRouter()
const globalStore = inject('globalStore')

const configs = ref([])
const loading = ref(false)
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref(null)
const addDialogVisible = ref(false)
const addLoading = ref(false)
const addFormRef = ref(null)

const editForm = ref({
  id: null,
  businessName: '',
  messageType: '',
  exchangeName: '',
  exchangeType: 'direct',
  queueName: '',
  routingKey: '',
  queueDurable: true,
  exchangeDurable: true,
  queueAutoDelete: false,

  maxRetryCount: 3,
  enabled: true,
  failureHandlerClass: '',
  remark: ''
})

const addForm = ref({
  businessName: '',
  messageType: '',
  exchangeName: '',
  exchangeType: 'direct',
  queueName: '',
  routingKey: '',
  queueDurable: true,
  exchangeDurable: true,
  queueAutoDelete: false,

  maxRetryCount: 3,
  enabled: true,
  failureHandlerClass: '',
  remark: ''
})

const addFormRules = {
  businessName: [
    {required: true, message: '请输入配置名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  messageType: [
    {required: true, message: '请输入消息类型', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  exchangeName: [
    {required: true, message: '请输入交换机名称', trigger: 'blur'}
  ],
  exchangeType: [
    {required: true, message: '请选择交换机类型', trigger: 'change'}
  ],
  queueName: [
    {required: true, message: '请输入队列名称', trigger: 'blur'}
  ],
  routingKey: [
    {required: true, message: '请输入路由键', trigger: 'blur'}
  ]
}

const editFormRules = {
  businessName: [
    {required: true, message: '请输入配置名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  messageType: [
    {required: true, message: '请输入消息类型', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  exchangeName: [
    {required: true, message: '请输入交换机名称', trigger: 'blur'}
  ],
  exchangeType: [
    {required: true, message: '请选择交换机类型', trigger: 'change'}
  ],
  queueName: [
    {required: true, message: '请输入队列名称', trigger: 'blur'}
  ],
  routingKey: [
    {required: true, message: '请输入路由键', trigger: 'blur'}
  ]
}

// 加载配置列表
const loadConfigs = async () => {
  loading.value = true
  try {
    const data = await mqConfigApi.getList()
    configs.value = data
    globalStore.clearMessages()
  } catch (error) {
    globalStore.setError('加载配置失败: ' + error.message)
  } finally {
    loading.value = false
  }
}



// 打开编辑弹框
const openEditDialog = async (config) => {
  try {
    // 获取配置详情
    const configDetail = await mqConfigApi.getById(config.id)

    // 填充表单数据
    editForm.value = {
      id: configDetail.id,
      businessName: configDetail.businessName || '',
      messageType: configDetail.messageType || '',
      exchangeName: configDetail.exchangeName || '',
      exchangeType: configDetail.exchangeType || 'direct',
      queueName: configDetail.queueName || '',
      routingKey: configDetail.routingKey || '',
      queueDurable: configDetail.queueDurable !== false,
      exchangeDurable: configDetail.exchangeDurable !== false,
      queueAutoDelete: configDetail.queueAutoDelete === true,

      maxRetryCount: configDetail.maxRetryCount || 3,
      enabled: configDetail.enabled !== false,
      failureHandlerClass: configDetail.failureHandlerClass || '',
      remark: configDetail.remark || ''
    }

    editDialogVisible.value = true



    // 等待弹框渲染完成后清除验证状态
    await nextTick()
    if (editFormRef.value) {
      editFormRef.value.clearValidate()
    }
  } catch (error) {
    ElMessage.error('获取配置详情失败: ' + error.message)
  }
}

// 更新配置
const updateConfig = async () => {
  if (!editFormRef.value) return

  try {
    const valid = await editFormRef.value.validate()
    if (!valid) return

    editLoading.value = true
    await mqConfigApi.update(editForm.value)

    ElMessage.success('配置更新成功')
    editDialogVisible.value = false
    await loadConfigs()
  } catch (error) {
    ElMessage.error('更新配置失败: ' + error.message)
  } finally {
    editLoading.value = false
  }
}

// 关闭编辑弹框
const handleEditDialogClose = () => {
  editDialogVisible.value = false
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 打开添加弹框
const openAddDialog = async () => {
  // 重置表单数据
  addForm.value = {
    businessName: '',
    messageType: '',
    exchangeName: '',
    exchangeType: 'direct',
    queueName: '',
    routingKey: '',
    queueDurable: true,
    exchangeDurable: true,
    queueAutoDelete: false,

    maxRetryCount: 3,
    enabled: true,
    failureHandlerClass: '',
    remark: ''
  }

  addDialogVisible.value = true

  // 等待弹框渲染完成后清除验证状态
  await nextTick()
  if (addFormRef.value) {
    addFormRef.value.clearValidate()
  }
}

// 添加配置
const addConfig = async () => {
  if (!addFormRef.value) return

  try {
    const valid = await addFormRef.value.validate()
    if (!valid) return

    addLoading.value = true
    await mqConfigApi.add(addForm.value)

    ElMessage.success('配置添加成功')
    addDialogVisible.value = false
    await loadConfigs()
  } catch (error) {
    ElMessage.error('添加配置失败: ' + error.message)
  } finally {
    addLoading.value = false
  }
}

// 关闭添加弹框
const handleAddDialogClose = () => {
  addDialogVisible.value = false
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
}

// 删除配置
const deleteConfig = async (id) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除这个配置吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    loading.value = true
    await mqConfigApi.delete(id)
    ElMessage.success('配置删除成功')
    await loadConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除配置失败: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadConfigs()
})
</script>

<style scoped>
.config-list {
  background: #f5f7fa;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 20px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e4e7ed;
}

.header-actions h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.header-actions h2::before {
  content: '';
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #409eff, #67c23a);
  border-radius: 2px;
  margin-right: 12px;
}

.el-table {
  background: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.el-table :deep(.el-table__header) {
  background: #f8f9fa;
}

.el-table :deep(.el-table__header th) {
  background: #f8f9fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 2px solid #e4e7ed;
}

.el-table :deep(.el-table__row:hover) {
  background: #f0f9ff;
}

.el-table :deep(.el-button) {
  margin-right: 8px;
  border-radius: 6px;
  font-weight: 500;
}

.el-table :deep(.el-button:last-child) {
  margin-right: 0;
}

.el-table :deep(.el-tag) {
  border-radius: 12px;
  font-weight: 500;
  border: none;
}

.empty-block {
  margin: 20px 0;
  text-align: center;
  background: #ffffff;
  padding: 40px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dialog-footer .el-button {
  border-radius: 6px;
  font-weight: 500;
  padding: 10px 20px;
}

:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-switch) {
  --el-switch-on-color: #67c23a;
}

:deep(.el-input-number .el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-textarea__inner:hover) {
  border-color: #c0c4cc;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}

@media (max-width: 768px) {
  .config-list {
    padding: 12px;
  }

  .header-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
    text-align: center;
    margin-bottom: 12px;
    padding: 8px 16px;
  }

  .header-actions h2 {
    font-size: 20px;
  }

  .el-table {
    font-size: 14px;
  }

  .el-table :deep(.el-table__cell) {
    padding: 8px 4px;
  }

  .el-table :deep(.el-button) {
    margin-bottom: 4px;
  }

  .empty-block {
    margin: 16px 0;
    padding: 30px 16px;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }

  .dialog-footer .el-button {
    width: 100%;
  }

  :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }

  :deep(.el-dialog__body) {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .header-actions {
    padding: 12px;
  }

  .header-actions h2 {
    font-size: 18px;
  }

  .el-table :deep(.el-button) {
    width: 100%;
    margin-bottom: 8px;
  }
}
</style>